from PIL import Image, ImageFilter
import logging

# 配置日志
logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s - %(levelname)s - %(message)s')

def apply_blur(image):
    """应用模糊效果."""
    logging.info("开始应用模糊效果")
    if not isinstance(image, Image.Image):
        logging.error("输入不是 PIL 图像对象")
        print("错误：输入不是 PIL 图像对象")
        return image

    try:
        blurred_image = image.filter(ImageFilter.BLUR)
        logging.info("模糊效果应用完成")
        return blurred_image
    except Exception as e:
        logging.exception(f"应用模糊效果失败: {e}")
        print(f"应用模糊效果失败: {e}")
        return image

def apply_edge_enhance(image):
    """应用边缘增强效果."""
    logging.info("开始应用边缘增强效果")
    if not isinstance(image, Image.Image):
        logging.error("输入不是 PIL 图像对象")
        print("错误：输入不是 PIL 图像对象")
        return image

    try:
        edge_enhanced_image = image.filter(ImageFilter.EDGE_ENHANCE)
        logging.info("边缘增强效果应用完成")
        return edge_enhanced_image
    except Exception as e:
        logging.exception(f"应用边缘增强效果失败: {e}")
        print(f"应用边缘增强效果失败: {e}")
        return image

def apply_emboss(image):
    """应用浮雕效果."""
    logging.info("开始应用浮雕效果")
    if not isinstance(image, Image.Image):
        logging.error("输入不是 PIL 图像对象")
        print("错误：输入不是 PIL 图像对象")
        return image

    try:
        embossed_image = image.filter(ImageFilter.EMBOSS)
        logging.info("浮雕效果应用完成")
        return embossed_image
    except Exception as e:
        logging.exception(f"应用浮雕效果失败: {e}")
        print(f"应用浮雕效果失败: {e}")
        return image

def apply_custom_filter(image, kernel):
    """应用自定义卷积核滤波."""
    logging.info(f"开始应用自定义滤波，卷积核: {kernel}")
    if not isinstance(image, Image.Image):
        logging.error("输入不是 PIL 图像对象")
        print("错误：输入不是 PIL 图像对象")
        return image

    if not isinstance(kernel, tuple) and not isinstance(kernel, list):
        logging.error("卷积核不是元组或列表")
        print("错误：卷积核不是元组或列表")
        return image

    try:
        # 将 kernel 转换为 ImageFilter.Kernel 需要的格式
        size = int(len(kernel)**0.5)
        if size * size != len(kernel):
            error_message = "卷积核大小必须是平方数"
            logging.error(error_message)
            print(f"错误：{error_message}")
            return image

        logging.debug(f"卷积核大小: {size}x{size}")
        kernel = ImageFilter.Kernel((size, size), kernel, scale=None, offset=0)
        filtered_image = image.filter(kernel)
        logging.info("自定义滤波应用完成")
        return filtered_image
    except ValueError as ve:
        logging.exception(f"值错误: {ve}")
        print(f"值错误: {ve}")
        return image
    except TypeError as te:
        logging.exception(f"类型错误: {te}")
        print(f"类型错误: {te}")
        return image
    except Exception as e:
        logging.exception(f"应用自定义滤波失败: {e}")
        print(f"应用自定义滤波失败: {e}")
        return image

def apply_sharpen(image):
    """应用锐化效果."""
    logging.info("开始应用锐化效果")
    if not isinstance(image, Image.Image):
        logging.error("输入不是 PIL 图像对象")
        print("错误：输入不是 PIL 图像对象")
        return image

    try:
        sharpened_image = image.filter(ImageFilter.SHARPEN)
        logging.info("锐化效果应用完成")
        return sharpened_image
    except Exception as e:
        logging.exception(f"应用锐化效果失败: {e}")
        print(f"应用锐化效果失败: {e}")
        return image

def apply_contour(image):
    """应用轮廓效果."""
    logging.info("开始应用轮廓效果")
    if not isinstance(image, Image.Image):
        logging.error("输入不是 PIL 图像对象")
        print("错误：输入不是 PIL 图像对象")
        return image

    try:
        contoured_image = image.filter(ImageFilter.CONTOUR)
        logging.info("轮廓效果应用完成")
        return contoured_image
    except Exception as e:
        logging.exception(f"应用轮廓效果失败: {e}")
        print(f"应用轮廓效果失败: {e}")
        return image

def apply_smooth(image):
    """应用平滑效果."""
    logging.info("开始应用平滑效果")
    if not isinstance(image, Image.Image):
        logging.error("输入不是 PIL 图像对象")
        print("错误：输入不是 PIL 图像对象")
        return image

    try:
        smoothed_image = image.filter(ImageFilter.SMOOTH)
        logging.info("平滑效果应用完成")
        return smoothed_image
    except Exception as e:
        logging.exception(f"应用平滑效果失败: {e}")
        print(f"应用平滑效果失败: {e}")
        return image

def apply_detail(image):
    """应用细节增强效果."""
    logging.info("开始应用细节增强效果")
    if not isinstance(image, Image.Image):
        logging.error("输入不是 PIL 图像对象")
        print("错误：输入不是 PIL 图像对象")
        return image

    try:
        detailed_image = image.filter(ImageFilter.DETAIL)
        logging.info("细节增强效果应用完成")
        return detailed_image
    except Exception as e:
        logging.exception(f"应用细节增强效果失败: {e}")
        print(f"应用细节增强效果失败: {e}")
        return image

def apply_gaussian_blur(image, radius=2):
    """应用高斯模糊效果."""
    logging.info(f"开始应用高斯模糊效果，半径: {radius}")
    if not isinstance(image, Image.Image):
        logging.error("输入不是 PIL 图像对象")
        print("错误：输入不是 PIL 图像对象")
        return image

    if not isinstance(radius, (int, float)) or radius <= 0:
        logging.error("半径必须是正数")
        print("错误：半径必须是正数")
        return image

    try:
        gaussian_blurred_image = image.filter(ImageFilter.GaussianBlur(radius))
        logging.info("高斯模糊效果应用完成")
        return gaussian_blurred_image
    except Exception as e:
        logging.exception(f"应用高斯模糊效果失败: {e}")
        print(f"应用高斯模糊效果失败: {e}")
        return image

def apply_min_filter(image, size=3):
    """应用最小值滤波."""
    logging.info(f"开始应用最小值滤波，大小: {size}")
    if not isinstance(image, Image.Image):
        logging.error("输入不是 PIL 图像对象")
        print("错误：输入不是 PIL 图像对象")
        return image

    if not isinstance(size, int) or size <= 0:
        logging.error("大小必须是正整数")
        print("错误：大小必须是正整数")
        return image

    try:
        min_filtered_image = image.filter(ImageFilter.MinFilter(size))
        logging.info("最小值滤波应用完成")
        return min_filtered_image
    except Exception as e:
        logging.exception(f"应用最小值滤波失败: {e}")
        print(f"应用最小值滤波失败: {e}")
        return image

def apply_max_filter(image, size=3):
    """应用最大值滤波."""
    logging.info(f"开始应用最大值滤波，大小: {size}")
    if not isinstance(image, Image.Image):
        logging.error("输入不是 PIL 图像对象")
        print("错误：输入不是 PIL 图像对象")
        return image

    if not isinstance(size, int) or size <= 0:
        logging.error("大小必须是正整数")
        print("错误：大小必须是正整数")
        return image

    try:
        max_filtered_image = image.filter(ImageFilter.MaxFilter(size))
        logging.info("最大值滤波应用完成")
        return max_filtered_image
    except Exception as e:
        logging.exception(f"应用最大值滤波失败: {e}")
        print(f"应用最大值滤波失败: {e}")
        return image

def apply_median_filter(image, size=3):
    """应用中值滤波."""
    logging.info(f"开始应用中值滤波，大小: {size}")
    if not isinstance(image, Image.Image):
        logging.error("输入不是 PIL 图像对象")
        print("错误：输入不是 PIL 图像对象")
        return image

    if not isinstance(size, int) or size <= 0:
        logging.error("大小必须是正整数")
        print("错误：大小必须是正整数")
        return image

    try:
        median_filtered_image = image.filter(ImageFilter.MedianFilter(size))
        logging.info("中值滤波应用完成")
        return median_filtered_image
    except Exception as e:
        logging.exception(f"应用中值滤波失败: {e}")
        print(f"应用中值滤波失败: {e}")
        return image